<?php

namespace app\common\model;

class PointsLog extends TimeModel
{

    protected $name = "points_log";

    protected $deleteTime = "delete_time";
    protected $defaultSoftDelete = 0;

    public function user()
    {
        return $this->hasOne(User::class, 'id', 'user_id');
    }

    public function orderR()
    {
        return $this->belongsTo(Order::class, 'relation_id', 'id');
    }

    //核算用户(当前店铺)可用积分
    public function getUsefulPoints($user_id, $shop_id = [])
    {

        $where = [];
        if ($shop_id) {
            $where['shop_id'] = $shop_id;
        }

        $time = time();
        //总共获取总数
        $get_num = self::where($where)
            ->where('user_id', $user_id)
            ->where('type', 1)
            ->sum('num');

        //先不计算 用户积分的有效期
        //当前有效积分总数
//        $get_num_userful = self::where($where)
//            ->where('user_id', $user_id)
//            ->where('type', 1)
//            ->sum('num');

        //总共花销总数
        $cost_num = self::where($where)
            ->where('user_id', $user_id)
            ->where('type', 2)
            ->sum('num');
        //如果积分显示 小于 0 则 显示0
//        $money = $get_num - $cost_num < $get_num_userful ? $get_num - $cost_num : $get_num_userful;
        $money = $get_num - $cost_num;
//        dd($get_num,$cost_num);
        return $money > 0 ? $money : 0;
    }

}